<?php

class CurrencyListWidget extends CWidget {

    public $visible = true;

    public function init() {
        
    }

    public function run() {
        if ($this->visible) {
            $this->renderContent();
        }
    }

    protected function renderContent() {
        $model = new Currency();
        settings()->deleteCache();
        // if it is ajax validation request
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'updateForm') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
        if (isset($_POST['updateAll'])) {
            $currency = Currency::model()->findAll();
            foreach ($currency as $cur) {
                $from = 'USD';
                $to = $cur->codeTo;
                $cc = new ECurrencyHelper();
                $rate = $cc->convert($from, $to, 1, ECurrencyHelper::USE_YAHOO);
                $cur = Currency::model()->findByAttributes(array('codeFrom' => $from, 'codeTo' => $to));
                $cur->conversionRate = $rate;
                $cur->updatedTime = time();

                if ($cur->save()) {
                    user()->setFlash('success', t('cms', 'Updated Successfully!'));
                }
            }
        }
        $this->render('cmswidgets.views.shopping.currency_list_widget', array('model' => $model));
    }

}
